#include <unistd.h>
#include <fcntl.h>
#include <iostream>
#include <cstdio>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <netinet/tcp.h>
#include <errno.h>
#include <cstring>
#include "InetAddress.h"
#include "Sock.h"
#include "Epoll.h"
#include "Channel.h"
#include"EpollEvent.h"

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        printf("usage: ./tcpepoll  port\n");
        printf("example: ./tcpepoll 8080\n\n");
        return -1;
    }

    Sock serverSock;
    uint16_t port = atoi(argv[1]);
    // 服务器的只需要这个port就行
    InetAddress servaddr(port);
    // 创建非阻塞的sock
    serverSock.cerateNonBlockingSocket();
    serverSock.setKeepAlive(true);
    serverSock.setReuseAddr(true);
    serverSock.setReusePort(true);
    serverSock.settcpnodelay(true);
    serverSock.bind(servaddr);
    serverSock.listen();

    // Epoll epoll;
    EventLoop loop;
    Channel *servchannel = new Channel(loop.getEpfd(), serverSock.getSock());
    servchannel->setReadCallBack(std::bind(&Channel::newconnection,servchannel,&serverSock));
    servchannel->enableReading();
    loop.run();
    // while (true)
    // {
    //     std::vector<Channel *> channels = epoll.loop(); // 等待监视的fd有事件发生。
    //     for (auto &ch : channels)
    //     {
    //         ch->handleevent();
    //     }
    // }

    return 0;
}